package com.xdwanj.criminalintent.fragment;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DatePickerFragment extends DialogFragment {
    private final String TAG = "DatePickerFragment";

    private static final String ARG_DATE = "date";

    private DatePickerFragment() {

    }

//    private Callbacks callbacks;

    public interface Callbacks {
        void onDateSelected(Date date);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        Calendar calendar = Calendar.getInstance();

        int initialYear = calendar.get(Calendar.YEAR);
        int initialMonth = calendar.get(Calendar.MONTH);
        int initialDay = calendar.get(Calendar.DAY_OF_MONTH);

        return new DatePickerDialog(
                requireContext(),
                (view, year, month, dayOfMonth) -> {
                    Date resultDate = new GregorianCalendar(year, month, dayOfMonth).getTime();

                    Log.d(TAG, "onCreateDialog: " + resultDate.toString());

                    if (getParentFragment() != null) { //获取父Fragment实例,判断非空
                        Log.d(TAG, "onCreateDialog: getParentFragment() not is null -> " + resultDate.toString());
                        ((Callbacks) getParentFragment()).onDateSelected(resultDate);
                    }
                },
                initialYear,
                initialMonth,
                initialDay
        );

    }

//    @Override
//    public void onAttach(@NonNull Context context) {
//        super.onAttach(context);
//        callbacks = (Callbacks) context;
//    }

    /**
     * 单例模式
     *
     * @param date 日期
     * @return 实例
     */
    public static DatePickerFragment newInstance(Date date) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_DATE, date);

        DatePickerFragment fragment = new DatePickerFragment();
        fragment.setArguments(args);

        return fragment;
    }
}
